package com.lei.dao.impl;

import com.lei.dao.UserDao;
import com.lei.domain.User;


import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName UserDaoImpl
 * @Description TODO
 * @Author Admin
 * @Date 2021/9/16 17:03
 * @Version 1.0
 */
public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> list() {
        List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    public long save(final User user) {
//        jdbcTemplate.update("insert into sys_user value (?,?,?,?,?)",null,user.getUsername(),user.getEmail(),user.getPassword(),user.getPhoneNum());
        PreparedStatementCreator creator=new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
               PreparedStatement preparedStatement=connection.prepareStatement("insert into sys_user value (?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
               preparedStatement.setObject(1,null);
               preparedStatement.setString(2, user.getUsername());
               preparedStatement.setString(3, user.getEmail());
               preparedStatement.setString(4, user.getPassword());
               preparedStatement.setString(5, user.getPhoneNum());
                return preparedStatement;
            }

        };
        GeneratedKeyHolder keyHolder=new GeneratedKeyHolder();
        jdbcTemplate.update(creator,keyHolder);
        long userId = keyHolder.getKey().longValue();
        return userId;
    }

    public void saveUserRoleRel(Long id, long[] roleIds) {
        for (int i = 0; i < roleIds.length; i++) {
            jdbcTemplate.update("insert into sys_user_role value (?,?)",id,roleIds[i]);
        }

    }

    public void delUserRoleRel(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userid=?",userId);
    }

    public void delUser(Long userId) {
        jdbcTemplate.update("delete from sys_user where id=?",userId);
    }
}
